package com.yqya.springboot.shiro.practice.biz.impl;

import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.yqya.springboot.shiro.practice.biz.RoleInfoBizService;
import com.yqya.springboot.shiro.practice.domain.RoleInfo;
import com.yqya.springboot.shiro.practice.domain.RoleRelatePermissionInfo;
import com.yqya.springboot.shiro.practice.dto.RoleInfoDTO;
import com.yqya.springboot.shiro.practice.service.RoleInfoService;
import com.yqya.springboot.shiro.practice.service.RoleRelatePermissionInfoService;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;

/**
 * 角色信息业务服务接口实现类
 *
 * @author Kevin
 * @date 2019-07-28
 */
@Service
public class RoleInfoBizServiceImpl implements RoleInfoBizService {

    @Autowired
    private RoleInfoService roleInfoService;

    @Autowired
    private RoleRelatePermissionInfoService roleRelatePermissionInfoService;

    @Override
    public RoleInfo save(RoleInfoDTO dto) {
        String name = dto.getName();
        List<Long> permissionIds = dto.getPermissionIds();

        // 保存角色信息
        RoleInfo item = new RoleInfo();
        item.setName(name);
        item.setCreateTime(DateUtil.date());
        roleInfoService.save(item);

        if (CollUtil.isNotEmpty(permissionIds)) {
            // 保存角色和权限的关系
            Long roleId = item.getId();
            List<RoleRelatePermissionInfo> roleRelatePermissionList = new LinkedList<>();
            for (Long permissionId : permissionIds) {
                RoleRelatePermissionInfo roleRelatePermission = new RoleRelatePermissionInfo();
                roleRelatePermission.setRoleId(roleId);
                roleRelatePermission.setPermissionId(permissionId);
                roleRelatePermission.setCreateTime(DateUtil.date());
                roleRelatePermissionList.add(roleRelatePermission);
            }
            roleRelatePermissionInfoService.saveBatch(roleRelatePermissionList);
        }

        return item;
    }

}
